const app = getApp();
import { getStorage } from "../../utils/localStorage"
import { selectTownShip, townRange_list, dynamiGive_option, listHotSpots_townShip, listTourismVillage_townShip, villageGoodsList_townShip } from "../../api/homePage"
import { shoppingCart_Add } from "../../api/shopping"
import { baseUrl } from "../../api/request"
import { getMapDistance } from "../../utils/address"
Component({
  data: {
    //图片ip地址  
    imgUrl: baseUrl,
    //自定义导航栏组件参数
    navData: {
      level: 2,
      title: '旅游乡镇'
    },

    //自定义导航栏高度
    pageTop: app.globalData.navHeight + app.globalData.navTop,
    swiper: {
      autoplay: true, //自动切换
      dots: true, //指示点
      dotsColor: "#ffffff", //指示点颜色
      dotsActiveColor: "#4646A0", //选中指示点颜色
      circular: true, //衔接滑动
      duration: 3000, //滑动动画时长
      boxFlag: false,
    },
    listQuery: {
      userId: null,
      pageSize: 10,
      pageNum: 1,
      townShipName: null
    },
    //乡镇名字
    townName: "",
    //乡镇地址
    townAddress: "",
    //列表总页数
    total: 0,
    //上拉加载更多状态
    showPull: true,
    //经纬度信息
    latlng: getStorage("latLng"),
    //用户信息
    user: getStorage("user"),
    //乡镇数据
    townData: {},
    //用户动态列表数据    
    list: [],
    // 用户动态列表左边显示数据
    leftList: [],
    //用户动态列表右边显示数据
    rightList: [],
    //热门景点列表
    attractionsList: [],
    //旅游乡村列表
    tourismVillageList: [],
    //乡村特产列表
    villageShopList: [],
  },
  lifetimes: {
    attached() {
      this.setData({
        user: getStorage("user"),
        imgUrl: baseUrl,
        latlng: getStorage("latLng"),
        "listQuery.userId": getStorage("user").id,
        "listQuery.townShipName": app.globalData.townName,
      });
      this.getTownData();
    },
    detached() { },
  },
  pageLifetimes: {
    show() {
      // if (app.globalData.detailPageType != "乡镇动态" && app.globalData.detailPageType != "乡镇详情" && app.globalData.detailPageType != "选择乡镇" &&
      //     app.globalData.detailPageType != "搜索") {
      //     this.setData({
      //         leftList: [],        // 用户动态列表左边显示数据
      //         rightList: [],
      //         townData: {},
      //         "listQuery.pageNum": 1,         //乡镇数据
      //         "listQuery.townShipName": app.globalData.townName,
      //     });
      //     this.getTownList();
      //     this.getUserDyunmisList();
      // };
      //动态点赞静态处理
      let dynamicId = app.globalData.dynamicId, dynamicGive = app.globalData.dynamicGive, dynamicGiveNum = app.globalData.dynamicGiveNum;
      if (dynamicId) {
        let indexFlag = this.data.leftList.findIndex(item => { return item.id === dynamicId }), index = null, value = null, num = null;
        if (indexFlag === -1) {
          index = this.data.rightList.findIndex(item => { return item.id === dynamicId });
          value = "rightList[" + index + "].likeState";
          num = "rightList[" + index + "].likeNumber";
        } else {
          index = this.data.leftList.findIndex(item => { return item.id === dynamicId });
          value = "leftList[" + index + "].likeState";
          num = "leftList[" + index + "].likeNumber";
        };
        this.setData({
          [value]: dynamicGive === 1 ? true : false,
          [num]: dynamicGiveNum,
        });
      };
    }
  },
  methods: {
    //获取入驻乡镇数据
    getTownData() {
      const _this = this.data;
      selectTownShip({ townShipName: _this.listQuery.townShipName, userId: _this.listQuery.userId }).then(res => {
        if (res.data.data) {
          res.data.data.imageScale = res.data.data.imageScale ? res.data.data.imageScale.split(",") : [];
          res.data.data.distance = getMapDistance(_this.latlng.lat, _this.latlng.lng, res.data.data.latitude, res.data.data.longitude);
          this.setData({
            townData: res.data.data,
            townName: res.data.data.townShipActivity,
            townAddress: res.data.data.townShipTitle,
          });
        };
        this.getAttractionsList();
      });
    },
    //获取热门景点列表
    getAttractionsList() {
      const _this = this.data;
      listHotSpots_townShip({ townShipName: _this.listQuery.townShipName }).then(res => {
        if (res.data.data) {
          let arr = res.data.data.map(item => ({
            ...item,
            imageScale: item.imageScale ? item.imageScale.split(",") : []
          }));
          this.setData({
            attractionsList: arr
          });
        };
        this.getTourismVillageList();
      });
    },
    //获取旅游乡村
    getTourismVillageList() {
      const _this = this.data;
      listTourismVillage_townShip({ townShipName: _this.listQuery.townShipName, longitude: _this.latlng.lng, latitude: _this.latlng.lat, }).then(res => {
        if (res.data.data) {
          let arr = res.data.data.map(item => ({
            ...item,
            villageLabel: item.villageLabel ? item.villageLabel.split(",") : [],
            villageImage: item.villageImage ? item.villageImage.split(",") : [],
          }));
          this.setData({
            tourismVillageList: arr
          });
        };
        this.getVillageShopList();
      });
    },
    //获取乡村特产
    getVillageShopList() {
      const _this = this.data;
      villageGoodsList_townShip({ userId: _this.listQuery.userId, townShipName: _this.listQuery.townShipName }).then(res => {
        if (res.data.data) {
          let arr = res.data.data.map(item => ({
            ...item,
            imageScale: item.imageScale ? item.imageScale.split(",") : []
          }));
          this.setData({
            villageShopList: arr
          });
        };
        this.getUserDyunmisList();
      });
    },
    //获取用户动态列表
    getUserDyunmisList() {
      let that = this.data;
      let leftArr = [], rightArr = [];
      townRange_list(that.listQuery).then(res => {
        if (!res.data.rows || res.data.rows.length === 0) {
          this.setData({
            leftList: [],
            rightList: [],
          })
        } else {
          res.data.rows.forEach((item, index) => {
            item.imageScale = item.imageScale.split(",");
            item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
            if (index % 2 === 0) {
              leftArr.push(item);
            } else {
              rightArr.push(item);
            };
          });
          this.setData({
            leftList: [...that.leftList, ...leftArr],
            rightList: [...that.rightList, ...rightArr],
            total: Math.ceil(res.data.total / that.listQuery.pageSize)
          });
        };
      });
    },
    //乡镇活动点击事件
    activityClick(e) {
      let item = e.currentTarget.dataset.item;
      let obj = { townName: item };
      wx.navigateTo({
        url: '/pagesShouYe/pages/search/index?item=' + encodeURIComponent(JSON.stringify(obj)),
      });
    },
    //乡镇查看详情点击事件
    townDetail(e) {
      let item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/xiangzhenDetail/index?id=' + item.townShipId,
      });
    },
    //用户动态点赞或取消点赞事件
    commentClick(e) {
      let that = this.data,
        item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index,
        title = e.currentTarget.dataset.title,
        flag = !item.likeState ? true : false;
      dynamiGive_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
        let state = "";
        let num = "";
        if (res.data.code === 200) {
          if (title === "leftList") {
            state = "leftList[" + index + "].likeState";
            num = "leftList[" + index + "].likeNumber";
          } else if (title === "rightList") {
            state = "rightList[" + index + "].likeState";
            num = "rightList[" + index + "].likeNumber";
          };
          this.setData({
            [state]: flag,
            [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
          });
        };
      });
    },
    //用户动态列表点击事件
    listTap(e) {
      let item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/listDetail/index?id=' + item.id + '&dynamicType=乡镇动态',
      });
    },
    //乡镇选择事件
    // townNameClick() {
    //     wx.navigateTo({
    //         url: '/pagesShouYe/pages/addressXz/index?name=' + this.data.townData.provCity + '&id=' + this.data.townData.mgyAreaCodeId,
    //     });
    // },
    //乡镇名称 picker
    townNameChange(e) {
      const arr = e.detail.value;
      app.globalData.townName = arr.toString();
      this.setData({
        "listQuery.pageNum": 1,
        "listQuery.townShipName": arr.toString()
      });
      this.getTownData();
    },

    //购物车图标按钮点击事件
    shoppingCartTap(e) {
      const item = e.currentTarget.dataset.item, _this = this.data;
      shoppingCart_Add({ goodsId: item.id, userId: _this.listQuery.userId, goodsCount: 1 }).then(res => {
        wx.showToast({
          icon: 'none',
          mask: true,
          title: res.data.msg,
          duration: 2000
        });
      });
    },

    //热门景点更多按钮点击事件
    rmjdMoreTap() {
      wx.navigateTo({
        url: '/pagesShouYe/pages/xiangzhenjingdian/index?townName=' + this.data.listQuery.townShipName,
      });
    },

    //热门景点列表点击事件
    rnjdListTap(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/jingquDetail/index?id=' + item.landscapesId,
      });
    },

    //旅游乡村更多按钮点击事件
    lyxcMoreTap() {
      const _this = this.data;
      wx.navigateTo({
        url: '/pagesShouYe/pages/xiangCun/index?townShipName=' + _this.listQuery.townShipName,
      });
    },

    //旅游乡村列表点击事件
    lyxcListTap(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/xaingcunDetail/index?id=' + item.villageId,
      });
    },

    //乡村特产按钮点击事件
    xctcMoreTap() {
      wx.navigateTo({
        url: '/pagesShangping/pages/index/index',
      });
    },

    //乡村特产列表点击事件
    xctcListTap(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShangping/pages/shoppingDetail/index?id=' + item.id,
      });
    },

    /* 上拉加载更多 */
    pullUp(e) {
      let that = this.data;
      if ((that.listQuery.pageNum + 1) <= that.total) {
        this.setData({
          showPull: false,
          "listQuery.pageNum": that.listQuery.pageNum += 1
        });
        this.getUserDyunmisList();
      } else {
        this.setData({
          showPull: true
        });
      };
    },
  }
})